package com.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.mapper.DoctorMapper;
import com.project.model.Doctor;
import com.project.model.User;
import com.project.service.DoctorService;
import com.project.service.UserService;
import com.project.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {

    private final UserService userService;

    @Override
    public Doctor getByUserId(Long userId) {
        return lambdaQuery()
            .eq(Doctor::getUserId, userId)
            .one();
    }

    @Override
    @Transactional
    public void audit(Long doctorId, Integer status, String reason) {
        Doctor doctor = getById(doctorId);
        if (doctor == null) {
            throw new BusinessException("医生信息不存在");
        }

        if (status == 2 && (reason == null || reason.trim().isEmpty())) {
            throw new BusinessException("驳回时必须填写原因");
        }

        // 更新医生状态
        doctor.setStatus(status);
        updateById(doctor);

        // 更新用户状态
        User user = userService.getById(doctor.getUserId());
        if (user != null) {
            user.setStatus(status == 1 ? 1 : 0); // 审核通过时启用用户
            userService.updateById(user);
        }
    }
} 